<!--  账务管理————————》  总部提现审核 -->
<template>
  <a-card :bordered="false">
    <!--    当前申请提现总金额（单位：元）   -->
    <div v-show="flag.notSysFlag" class="table-page-search-wrapper">
      <span>当前申请提现总金额（单位：元）：{{ balance.totalBalance }}</span>
    </div>
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :lg="6" :md="8" :sm="12" :xs="24">
            <a-form-item label="记录时间">
              <a-date-picker valueFormat="YYYY-MM-DD HH:mm:ss" v-model="queryParam.createTime" placeholder="请选择记录时间" />
            </a-form-item>
          </a-col>

          <a-col :lg="6" :md="8" :sm="12" :xs="24">
            <a-form-model-item label="分站：" prop="siteId">
              <a-select placeholder="请选择分站" v-model="queryParam.siteId" show-search :showArrow="false" allowClear :filter-option="filterSelectOption" @change="changeSiteId">
                <a-select-option v-for="item in siteList" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :lg="6" :md="8" :sm="12" :xs="24">
            <a-form-model-item label="审核状态" prop="withdrawCashStatus">
              <j-dict-select-tag placeholder="请选择" v-model="queryParam.withdrawCashStatus" dictCode="bill_withdraw_cash_status" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="6" :md="8" :sm="12" :xs="24">
            <a-form-model-item label="批量审核单号" prop="auditNo">
              <a-input placeholder="请选择" v-model="queryParam.auditNo" />
            </a-form-model-item>
          </a-col>

          <template v-if="toggleSearchStatus">
            <a-col :lg="6" :md="8" :sm="12" :xs="24">
              <a-form-model-item label="商家：" prop="merchantId">
                <a-select placeholder="请选择商家" v-model="queryParam.merchantId" show-search :showArrow="false" allowClear :filter-option="merchantIdSelectOption" @change="changeMerchantId" :disabled="!queryParam.siteId">
                  <a-select-option v-for="item in merchantList" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :lg="6" :md="8" :sm="12" :xs="24">
              <a-form-model-item label="门店：" prop="shopId">
                <a-select placeholder="请选择门店" v-model="queryParam.shopId" show-search :showArrow="false" allowClear :filter-option="basicIdSelectOption" :disabled="!queryParam.merchantId">
                  <a-select-option v-for="item in shoplist" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('系统审核')">导出</a-button>
    </div>

    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
        selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-table ref="table" size="middle" :scroll="{ x: true }" bordered rowKey="id" :columns="columns" :dataSource="dataSource" :pagination="ipagination" :loading="loading" class="j-table-force-nowrap" @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
          <a @click="detail(record)">审核</a>
        </span>
      </a-table>
      <a-drawer :title="check.title" placement="right" :closable="false" :visible="check.flag" @close="checkCancel" width="500">
        <a-card title="账单行基本信息" :bordered="true" style="width:100%">
          <a-row>
            <a-col :span="3">分站：</a-col>
            <a-col :span="7">{{ check.info.siteName }}</a-col>
            <a-col :span="4">商家：</a-col>
            <a-col :span="10">{{ check.info.merchantName }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="3">门店：</a-col>
            <a-col :span="7">{{ check.info.shopName }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="4">订单号：</a-col>
            <a-col :span="20">{{ check.info.orderNo }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="5">实付金额：</a-col>
            <a-col :span="6">{{ check.info.payAmount }}</a-col>
            <a-col :span="5">佣金比例：</a-col>
            <a-col :span="6">{{ check.info.rakeRatePre }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="6">结算时间：</a-col>
            <a-col :span="12">{{ check.info.createTime }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="6">结算后收益：</a-col>
            <a-col :span="10">{{ check.info.rakeAmount }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="6">提现发起人：</a-col>
            <a-col :span="10">{{ check.info.txfqr }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="8">提现人支付宝姓名：</a-col>
            <a-col :span="16">{{ check.info.rakeAliname }}</a-col>
          </a-row>
          <a-row>
            <a-col :span="8">提现人支付宝账号：</a-col>
            <a-col :span="16">{{ check.info.rakeAlipay }}</a-col>
          </a-row>
        </a-card>
        <div>
          <p>各方收益展示：</p>
          <p v-for="(item,key) in check.billLines" :key="key">
            {{ item.type == 1 ? '系统' : item.type == 2 ? '分站' : '商家（门店）' }}，收益比例：{{ item.rakeRate
            }}，收益金额：{{ item.rakeAmount }}</p>
        </div>
        <!--  时间轴方式展示   -->
        <div>
          <p>各时间节点操作信息：</p>
          <a-timeline mode="alternate">
            <a-timeline-item v-for="(item, key) in check.billLineHistories" :key="key">{{ item.createTime }}
              ({{ item.withdrawCashStatus == 1 ? '结算' : item.withdrawCashStatus == 2 ? '发起提现待平台审核' :
              item.withdrawCashStatus == 3 ? '提现申请审核通过待转账' :
              item.withdrawCashStatus == 4 ? '提现申请被驳回' : item.withdrawCashStatus == 5 ? '（提现）转账成功' : '（提现）转账失败' }})
            </a-timeline-item>
          </a-timeline>
        </div>
        <!-- 平台审核 -->
        <div>
          <p>平台审核</p>
          <a-radio-group v-model="check.outcome.status" @change="checkRadioChange">
            <a-radio :value="3">
              审核通过(待平台转账)
            </a-radio>
            <a-radio :value="4">
              驳回
            </a-radio>
          </a-radio-group>
          <a-button type="primary" @click="saveCheckRelt">保存审核结果</a-button>
        </div>
        <!-- 转账 -->
        <div>
          <a-button type="primary" @click="checkOrder">核查订单</a-button>
          <a-button :disabled=check.transferAccountsFlag type="primary" style="margin-left: 20px;" @click="transferAccounts">转账
          </a-button>
        </div>
      </a-drawer>
    </div>
  </a-card>

</template>
<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JVxeRadioCell from '../../components/JVxeCells/JVxeRadioCell'
import { postAction, getAction } from '../../api/manage'
import store from '@/store'
export default {
  name: 'BillList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    JVxeRadioCell
    //SiteModal
  },
  data() {
    return {
      sysCheckBatchVisible: false,
      description: '收入列表',
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '分站',
          align: 'center',
          dataIndex: 'siteName'
        },
        {
          title: '商家',
          align: 'center',
          dataIndex: 'merchantName'
        },
        {
          title: '门店',
          align: 'center',
          dataIndex: 'shopName'
        },
        {
          title: '订单号',
          align: 'center',
          dataIndex: 'orderNo'
        },
        {
          title: '实付金额',
          align: 'center',
          dataIndex: 'payAmount'
        },
        {
          title: '佣金比例',
          align: 'center',
          dataIndex: 'rakeRate',
          customRender: (t) => {
            return t * 100 + '%'
          }
        },
        {
          title: '本单收益',
          align: 'center',
          dataIndex: 'rakeAmount'
        },
        {
          title: '批量审核单号',
          align: 'center',
          dataIndex: 'auditNo'
        },
        {
          title: '审核状态',
          align: 'center',
          dataIndex: 'withdrawCashStatus',
          customRender: function (t, r, index) {
            let color
            switch (t) {
              case 1:
                color = 'orange'
                break
              case 2:
                color = 'purple'
                break
              case 3:
                color = 'blue'
                break
              case 4:
                color = 'pink'
                break
              case 5:
                color = 'green'
                break
              case 6:
                color = 'red'
                break
            }
            return color ? <a-tag
              color={color}>{r.withdrawCashStatus_dictText}</a-tag> : r.withdrawCashStatus_dictText
          }
        },
        {
          title: '提现类型',
          align: 'center',
          dataIndex: 'type_dictText'
        },
        {
          title: '结算时间',
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: '申请提现时间',
          align: 'center',
          dataIndex: 'withdrawTime'
        },
        {
          title: '提现审核时间',
          align: 'center',
          dataIndex: 'withdrawApplyCheckTime'
        },
        /*{
          title: '驳回原因(审核状态被驳回时才会有值)',
          align: "center",
          dataIndex: 'withdrawRejectReason',
        },*/
        {
          title: '结算时支付宝姓名',
          align: 'center',
          dataIndex: 'rakeAliname'
        },
        {
          title: '结算时支付宝账号',
          align: 'center',
          dataIndex: 'rakeAlipay'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: '100px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      dataSource1: [],
      columns1: [{
        title: '序号',
        dataIndex: '',
        key: 'rowIndex',
        width: 60,
        align: 'center',
        customRender: function (t, r, index) {
          return parseInt(index) + 1
        }
      },
      {
        title: '批量审核单号',
        align: 'center',
        dataIndex: 'auditNo'
      },
      {
        title: '账单数量',
        align: 'center',
        dataIndex: 'num'
      },],
      // 右侧表头
      url: {
        list: '/finance/bill/withdrawCash/sysCheck/list',
        allSite: '/merchant/certification/allSite',
        merchantAllList: '/merchant/certification/merchantAllList',
        exportXlsUrl: '/finance/bill/withdrawCash/sysCheck/exportXls',
        listAll: '/shop/shopBasic/listAll',
        findBillLineHistoryByBillLineId: '/finance/bill/withdrawCash/income/lineHistoryByBillLineId',
        findBillLineByOrderNo: '/finance/bill/withdrawCash/income/billLineByOrderNo',
        sysCheck: '/finance/bill/withdrawCash/income/application/check',

        findBillLineById: '/finance/bill/withdrawCash/income/billLineByBillLineId',
        transfer: '/finance/bill/withdrawCash/income/application/transfer',
        batchAudit: '/finance/bill/withdrawCash/income/application/batchAudit'
      },
      siteList: [],//分站列表
      merchantList: [], // 商家列表
      shoplist: [],//门店列表
      /* table选中keys*/
      // selectedRowKeys: [],
      /* table选中records*/
      // selectionRows: [],
      usertype: undefined,
      flag: {
        sysFlag: false,
        notSysFlag: false
      },
      oneBalance: {},
      balance: {},
      check: {
        title: '',
        flag: false,
        info: {},
        billLineHistories: [],
        billLines: [],
        // 审核结果
        outcome: {},
        transferAccountsFlag: true
      }
    }
  },
  created() {
    if (this.$route.query.auditNo) {
      this.queryParam.auditNo = this.$route.query.auditNo;
    }
    const self = this
    self.usertype = store.getters.userInfo.userType
    // 2代表：已提出提现申请待总部审核、3代表：提现申请审核通过待转账、4代表：提现申请被驳回、
    if (self.usertype == 1) {
      self.getallsite()
      self.flag.sysFlag = true
    } else if (self.usertype == 2) {
      self.queryParam.siteId = store.getters.userInfoSite.id
      self.getallmerchant()
      self.flag.notSysFlag = true
    } else if (self.usertype == 3) {
      self.queryParam.siteId = store.getters.userInfoSite.id
      self.queryParam.merchantId = store.getters.userInfoMerchant.id
      self.getallBasic()
      self.flag.notSysFlag = true
    }
    self.queryParam = JSON.parse(JSON.stringify(self.queryParam))
    // 查询余额
    this.searchQuery()
  },
  computed: {},
  watch: {},
  methods: {
    // 获取当前登录用户的的余额列表
    billDetailBtn() {
      this.$message.info('查看待提现账单信息')
    },
    onChange(date, dateString) {
      console.log(date, dateString)
      // this.queryParam.createTime = date
    },
    changeSiteId() {
      this.merchantList = []
      this.shoplist = []
      this.queryParam.merchantId = undefined
      this.queryParam.shopId = undefined
      this.queryParam = JSON.parse(JSON.stringify(this.queryParam))
      if (this.queryParam.siteId) {
        this.getallmerchant()
      }
    },
    changeMerchantId() {
      this.shoplist = []
      this.queryParam.shopId = undefined
      this.queryParam = JSON.parse(JSON.stringify(this.queryParam))
      if (this.queryParam.merchantId) {
        this.getallBasic()
      }
    },
    // 输入筛选 分站
    filterSelectOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 输入筛选 商铺
    merchantIdSelectOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 输入筛选门店
    basicIdSelectOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取所有分站
    getallsite() {
      const self = this
      self.siteList = []
      getAction(self.url.allSite, {}).then(res => {
        console.log(res)
        if (res.success) {
          self.siteList = res.result
        } else {
          self.$message.warning(res.message)
        }
      })
    },
    // 获取分站下所有商铺
    getallmerchant() {
      const self = this
      self.merchantList = []
      getAction(self.url.merchantAllList, { siteId: this.queryParam.siteId }).then(res => {
        console.log(res)
        if (res.success) {
          self.merchantList = res.result
        } else {
          self.$message.warning(res.message)
        }
      })
    },
    // 获取分站下当前商铺的所有门店
    getallBasic() {
      const self = this
      self.shoplist = []
      getAction(self.url.listAll, { merchantId: this.queryParam.merchantId }).then(res => {
        console.log(res)
        if (res.success) {
          self.shoplist = res.result
        } else {
          self.$message.warning(res.message)
        }
      })
    },
    detail(record) {
      console.log('record---->    ', record)
      const self = this
      // 获取账单行历史记录
      self.selectLineHistory(record.id)
      // 获取账单行信息（各方分润）
      self.selectLineByOrderNo(record.orderNo)
      const type = record.type
      self.check.info = record
      self.check.title = '申请提现，订单号：' + record.orderNo + ''
      if (type == 2) {
        // 分站
        self.check.title = record.siteName + ' 申请提现，订单号：' + record.orderNo
        self.check.info.txfqr = '分站'
      }
      if (type == 3) {
        // 商家（根据门店提现）
        self.check.title = record.merchantName + ' ' + record.shopName + ' 申请提现，订单号：' + record.orderNo
        self.check.info.txfqr = '商家（门店）'
      }
      self.check.info.rakeRatePre = record.rakeRate * 100 + '%'
      self.check.flag = true

      self.check.outcome.id = record.id

      // 提现按钮是否可用
      self.check.transferAccountsFlag = true
      if (record.withdrawCashStatus == 3) {
        self.check.transferAccountsFlag = false
      }
      console.log('self.check.transferAccountsFlag== ', self.check.transferAccountsFlag)
    },
    selectLineHistory(recordId) {
      const self = this
      getAction(self.url.findBillLineHistoryByBillLineId, { billLineId: recordId }).then(res => {
        console.log(res)
        if (res.success) {
          self.check.billLineHistories = res.result
          console.log('self.check.billLineHistories===  ', self.check.billLineHistories)
        } else {
          self.$message.warning('获取账单行历史信息失败！')
        }
      })
    },
    selectLineByOrderNo(orderNo) {
      const self = this
      getAction(self.url.findBillLineByOrderNo, { orderNo: orderNo }).then(res => {
        console.log(res)
        if (res.success) {
          self.check.billLines = res.result
          console.log('self.check.billLines---> ', self.check.billLines)
        } else {
          self.$message.warning('获取账单结算信息失败！')
        }
      })
    },
    checkCancel() {
      this.check.title = ''
      this.check.flag = false
      this.searchQuery()
    },
    checkRadioChange(e) {
      console.log('val===? ', e.target.value)
      this.check.outcome.withdrawCashStatus = e.target.value
    },
    saveCheckRelt() {
      const self = this
      console.log('self.check.outcome---->    ', self.check.outcome)
      postAction(self.url.sysCheck, {
        id: self.check.outcome.id,
        withdrawCashStatus: self.check.outcome.withdrawCashStatus
      }).then(res => {
        if (res.success) {
          // 重新加载历史记录
          self.selectLineHistory(self.check.outcome.id)
          // 根据账单行id查询账单行信息
          getAction(self.url.findBillLineById, { billLineId: self.check.outcome.id }).then(res => {
            if (res.success) {
              console.log('saveCheckRelt------res   ', res)
              console.log('saveCheckRelt------res.result   ', res.result)
              self.detail(res.result)
            }
          })
        } else {
          self.$message.warning('审核失败！')
        }
      })
    },
    checkOrder() {
      // 核查订单
      console.log('订单号= ', this.check.info.orderNo)
    },
    transferAccounts() {
      //转账，支付宝转账
      const self = this
      console.log('账单信息= ', this.check.info)
      postAction(self.url.transfer, { id: self.check.outcome.id }).then(res => {
        if (res.success) {
          self.$message.info('提现成功')
          self.check.transferAccountsFlag = false
          // TODO 关闭页面
        }
      })
    }
  }

}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>